package com.zhou.controller;

import com.alibaba.fastjson.JSON;
import com.zhou.constant.ESConst;
import com.zhou.vo.Result;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("es")
public class ElasticsearchTest {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @RequestMapping("index")
    public Result index() throws Exception{
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(ESConst.INDEX_TEST);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        return new Result().data(createIndexResponse);
    }

    @RequestMapping("update")
    public Result update() throws Exception{
        UpdateRequest updateRequest = new UpdateRequest(ESConst.INDEX_TEST,ESConst.ID_TEST);
        Map m = new HashMap();
        m.put("name","zhangsan");
        m.put("age","10000");
        m.put("remark","jisuhiwan");
        m.put("level","-10");
        String json = JSON.toJSONString(m);
        updateRequest.docAsUpsert(true);
        updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        updateRequest.doc(json, XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return new Result();
    }


    @RequestMapping("save")
    public Result save() throws Exception{
        IndexRequest indexRequest = new IndexRequest(ESConst.INDEX_TEST);
        indexRequest.id(ESConst.ID_TEST);

        Map m = new HashMap();
        m.put("name","zhangsan");
        m.put("age","10000");
        m.put("remark","jisuhiwan");
        m.put("level","-10");
        String json = JSON.toJSONString(m);

        indexRequest.source(json, XContentType.JSON);
//        UpdateResponse update = restHighLevelClient.update(indexRequest, RequestOptions.DEFAULT);
        return new Result();
    }
}
